<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button-group>
        <el-button :type="filterForm.remove == 1?'success':'default'" @click="handleFilter();filterForm.remove=1;">全部</el-button>
        <el-button :type="filterForm.remove == 3?'success':'default'" @click="handleFilter();filterForm.remove=3">我的任务</el-button>
        <el-button :type="filterForm.remove == 2?'success':'default'" @click="handleFilter();filterForm.remove=2;">回收站</el-button>
      </el-button-group>
    </div>
    <div class="filter-container">
      <el-form ref="filterForm" :model="filterForm" :inline="true" label-position="left" label-width="100px">
        <el-form-item label="关键字" prop="keyword">
          <el-input v-model="filterForm.keyword" placeholder="任务ID/任务标题/任务介绍" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
        </el-form-item>
        <el-form-item label="发布时间" prop="publishTime">
          <el-date-picker 
            v-model="filterForm.publishTime"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="作者" prop="employee">
          <el-input v-model="filterForm.employee" placeholder="作者ID/作者电话/作者别名" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
            <el-select v-model="filterForm.status" placeholder="请选择">
              <el-option label="0" value="0">全部</el-option>
              <el-option label="6" value="6">正常</el-option>
              <el-option label="6" value="5">禁用</el-option>
              <el-option label="1" value="1">草稿</el-option>
            </el-select>
        </el-form-item>
        <el-form-item>
            <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
              搜索
            </el-button>
            <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
              新建
            </el-button>
            <el-button class="filter-item" style="margin-left: 10px;" type="danger" icon="el-icon-delete" @click="handleRemove">
              删除
            </el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      :row-class-name="tableRowClassName"
      @sort-change="sortChange"
      @selection-change="handleSelectionChange"
    >
    <el-table-column
      type="selection"
      width="55">
    </el-table-column>
      <el-table-column label="名称" align="left" min-width="200" fixed="left">
        <template slot-scope="{row}">
          <span class="link-type" @click="handleShow(row)">{{ row.title }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" max-width="150px">
        <template slot-scope="{row}">
          <span>{{ row.status.label }}</span>
        </template>
      </el-table-column>
      <el-table-column label="触发器" max-width="200" align="left">
        <template slot-scope="{row}">
            {{ row.setting }}
        </template>
      </el-table-column>
      <el-table-column label="下次运行时间" class-name="status-col" width="180">
        <template slot-scope="{row}">
            {{ row.nextTime }}
        </template>
      </el-table-column>
      <el-table-column label="上次运行时间" class-name="status-col" width="180">
        <template slot-scope="{row}">
            {{ row.prevTime }}
        </template>
      </el-table-column>
      <el-table-column label="上次运行结果" width="300" max-height="100">
        <template slot-scope="{row}">
            {{ row.outcome }}
        </template>
      </el-table-column>
      <el-table-column label="创建人" width="300" max-height="100">
        <template slot-scope="{row}">
            {{ row.employee.fullname }}
        </template>
      </el-table-column>
      <el-table-column label="操作" class-name="status-col" width="300" fixed="right">
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button v-if="row.status.value == 6" type="waring" size="mini" @click="handleModifyStatus(row,5)">
            禁用
          </el-button>
          <el-button v-if="row.status.value != 6 " size="mini" @click="handleModifyStatus(row,6)">
            启用
          </el-button>
          <el-button v-if="row.status.value == 1 || row.status.value == 5" size="mini" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="filterForm.page" :limit.sync="filterForm.size" @pagination="getList" />

  </div>
</template>

<script>
import { getMissionList,removeMission,changeStatusMission  } from '@/api/foundation/mission'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

export default {
  name: 'knowledgeAdmin',
  components: { Pagination },
  directives: { waves },
  filters: {
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      selectedIDs:[],
      filterForm: {
        remove:1,
        page: 1,
        size: 10,
        keyword: undefined,
        sort: '+id'
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
  tableRowClassName({row, rowIndex}) {
      if (row.status.value === 5) {
        return 'warning-row';
      } else if (row.remove === 2) {
        return 'warning-row';
      }
      return '';
    },
    getList() {
      this.listLoading = true
      getMissionList(this.filterForm).then(response => {
        this.list = response.data.list
        this.total = response.data.total

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    handleSelectionChange:function(itemList){
      this.selectedIDs = []
      itemList.forEach((item)=>{
        this.selectedIDs.push(item.ID)
      });
    },
    handleShow:function(item){
      this.$router.push({ path: 'mission-detail', query: { 'missionID': item.ID }})
    },
    handleCreate:function(){
      this.$router.push({ path: 'mission-add'})
    },
    handleUpdate:function(item){
      let fullPath = this.$route.fullPath.split('/')
      fullPath.pop()
      fullPath.pop()
      fullPath.push('mission-add')
      fullPath = fullPath.join('/')
      console.log(fullPath)
      this.$router.push({ path: fullPath, query: { 'missionID': item.ID }})
    },
    handleModifyStatus(row, status) {
      console.log(this.selectedIDs)
      changeStatusMission({
        "missionID":row.ID,
        "status":status
      }).then((response) => {
          if (response.code === 200) {
            this.$message({
              message: '操作Success',
              type: 'success'
            })
            this.getList()
          } else {
            this.$message({
              message: response.msg,
              type: 'error'
            })
          }
      })
    },
    handleRemove:function(){
        const _this = this
        const formData = {
          'companyID': this.selectedIDs
        }
        removeMission(formData).then(response => {
          if (response.status === 200) {
            this.$message({
              message: '操作Success',
              type: 'success'
            })
            // _this.filterForm.start = 1
            _this.getList()
            _this.selectedIDs = []
          } else {
            this.$message({
              message: response.msg,
              type: 'error'
            })
          }
        })
    },
    handleDelete(row) {
      removeMission({"missionID":row.ID}).then((response) => {
          if (response.code === 200) {
            this.$message({
              message: '操作Success',
              type: 'success'
            })
            this.getList()
          } else {
            this.$message({
              message: response.msg,
              type: 'error'
            })
          }
      })
    },
    handleFilter() {
      this.filterForm.page = 1
      this.getList()
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.filterForm.sort = '+id'
      } else {
        this.filterForm.sort = '-id'
      }
      this.handleFilter()
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.filterForm.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>
<style>
  .el-table .warning-row {
    background: rgb(250, 163, 128);
  }

  .el-table .success-row {
    background: #c8f5b3;
  }
</style>